package com.saikei.demoapp.util

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import androidx.fragment.app.Fragment
import kotlinx.serialization.Serializable

object IntentUtils {

    fun obtainArg(vararg args: Any): Bundle {
        val bundle = Bundle()
        val size = args.size
        var key: String
        var value: Any?
        var i = 0
        while (i < size) {
            key = args[i].toString()
            value = args[i + 1]
            when (value) {
                is CharSequence -> bundle.putString(key, value.toString())
                is Boolean -> bundle.putBoolean(key, value)
                is Int -> bundle.putInt(key, value)
                is Parcelable -> bundle.putParcelable(key, value)
                is Serializable -> bundle.putSerializable(key, value as java.io.Serializable?)
                is List<*> -> {
                    when {
                        value.isNotEmpty() && value[0] is String ->
                            bundle.putStringArrayList(key, ArrayList(value as List<String>))
                        value.isNotEmpty() && value[0] is Parcelable ->
                            bundle.putParcelableArrayList(key, ArrayList(value as List<Parcelable>))
                    }
                }
            }
            i += 2
        }
        return bundle
    }

    fun contextObjToContext(contextObj: Any?): Context? = when (contextObj) {
        is Fragment -> contextObj.activity
        is Activity -> contextObj
        is Context -> contextObj
        else -> null
    }
}
